//
//  UserLoginViewController.m
//  much
//
//  Created by weijunjie on 2019/1/2.
//  Copyright © 2019年 iOS. All rights reserved.
//

#import "UserLoginViewController.h"
#import "UserLoginView.h"
#import "UserIdentifyCodeView.h"
#import "MuchUserRequestManager.h"

@interface UserLoginViewController()
@property (nonatomic, strong) UserLoginView *loginView;
@property (nonatomic, strong) UserIdentifyCodeView *identifyCodeView;
@end

@implementation UserLoginViewController

- (void)_reLayout {
    [self.navigationView setTitle:@"登录"];
    [self addBackItem];
    [self loginView];
}

- (void)addBackItem {
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setImage:[UIImage imageNamed:@"navigation_back"] forState:UIControlStateNormal];
    __weakConfigure
    [self.navigationView addCustomView:backButton makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.bottom.mas_equalTo(0);
        make.width.mas_equalTo(9);
        make.height.mas_equalTo(44);
    } callback:^(UIView *view) {
        [__weakSelf dismissViewControllerAnimated:NO completion:nil];
    }];
}

- (UserLoginView *)loginView {
    if (!_loginView) {
        _loginView = [[UserLoginView alloc] init];
        [self.view addSubview:_loginView];
        [_loginView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(self.view);
            make.top.equalTo(self.view).offset(self.navigationView.height);
        }];
        __weakConfigure
        _loginView.login = ^(NSString * _Nonnull identity) {
            __weakSelf.identifyCodeView.identity = identity;
        };
    }
    return _loginView;
}

- (UserIdentifyCodeView *)identifyCodeView {
    [_identifyCodeView removeFromSuperview];
    _identifyCodeView = [[UserIdentifyCodeView alloc] init];
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:_identifyCodeView];
    [_identifyCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(keyWindow);
    }];
    __weakConfigure
    _identifyCodeView.inputViewBlock = ^(NSString *codeNum, NSString *phoneNum) {
        // 登录
        [__weakSelf requestLoginWithIdentity:phoneNum captcha:codeNum];
    };
    
    return _identifyCodeView;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - request
- (void)requestLoginWithIdentity:(NSString *)identity
                         captcha:(NSString *)captcha {
    [SVProgressHUD showWithStatus:@"登录中..."];
    [MuchUserRequestManager userLoginWithIdentity:identity captcha:captcha successBlock:^(id responseObject) {
        [self.identifyCodeView removeFromSuperview];
        [self dismissViewControllerAnimated:NO completion:nil];
        
        // 保存登录信息
        USER.userBaseInfo = [UserBaseInfo modelWithDictionary:responseObject];
        
    } failureBlock:nil];
}

@end
